//
//  ShoppingCarVC.m
//  夺宝吧
//
//  Created by xiaocai on 15/6/15.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "ShoppingCarVC.h"
#import "ShoppingCarCell.h"
#import "PayView.h"
#import "WYAlertView.h"
#import "IntrestView.h"
#import "MJRefresh.h"
#import "EditFooterView.h"


#define ALL_PDC_URL @"/api/ApiGoods/getLatestGoodsListForCart"
@interface ShoppingCarVC ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>
{
    //底部控件
    PayView *_footer;
    //购物车为空的显示的界面
    IntrestView *_intrestView;
    //记录原始偏移值
    CGPoint s_contOffet;

    
    //编辑按钮
    UIButton *editBtn;
    //编辑footer
    EditFooterView *editFooter;
}
@end

@implementation ShoppingCarVC
//获取购物车界面的单例
+ (ShoppingCarVC *)shareShoppingCarVC
{
    static ShoppingCarVC *staticShopVC = nil;
    
   static  dispatch_once_t once;
    dispatch_once(&once, ^{
        staticShopVC = [[ShoppingCarVC alloc]init];
    });
    return staticShopVC;
}

#pragma  mark --  viewDidLoad  viewWillAppear
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];

    self.firstFlag = YES;
    // Do any additional setup after loading the view.
    //加载导航条
    [self loadCustomNaviBar];
    //加载底部结算信息控件
    [self loadBottomView];
    //加载表格
    [self loadTableView];
    
}

#pragma mark -- viewWillAppear

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [[WYMainTabBarVC shareMainTaBarVC]updateCountToCar];
    if (self.firstFlag) {
//       NSMutableArray*  tmpdata = [[NSMutableArray alloc]initWithArray:[[WYDataBase sharedDataBase]getAllpdcInCar]];
        _data = [[NSMutableArray alloc]initWithArray:[[WYDataBase sharedDataBase]getAllpdcInCar]];

        if (_data.count > 0) {
            //自动刷新(一进入程序就下拉刷新)
            [_tableView headerBeginRefreshing];
        }else{
            [_intrestView removeFromSuperview];
            //创建购物车信息为空时的界面
            [self loadIntrestView];
        }
        
    }
    self.firstFlag = YES;
}

//创建购物车信息为空时的界面
- (void)loadIntrestView
{
    _intrestView = [[IntrestView alloc]initWithFrame:CGRectMake(0, 64, WYMWITH, WYMHEIGHT - 64 - 49)];
    _intrestView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_intrestView];
}


//- (void)viewDidDisappear:(BOOL)animated
//{
//    [_data removeAllObjects];
//}
//请求剩余数量
- (void)requestForNum
{
    NSString *ids=@"";
    for (WYShopCarModel *model in _data) {
        if (ids.length != 0) {
            ids = [ids stringByAppendingString:[NSString stringWithFormat:@",%@",model.car_new_id]];
        }else{
            ids = [NSString stringWithFormat:@"%@",model.car_new_id];
        }
        
    }
    //禁用支付按钮
    _footer.PayBtn.enabled = NO;
    
    NSDictionary *params = @{@"ids":ids};
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,ALL_PDC_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        NSDictionary *pdcs = dic[@"data"];
        NSArray *keys = [pdcs allKeys];
       
//            NSInteger index = 0;
        
        NSMutableArray *tmpdata =  [_data copy];
        NSMutableArray *tmpArray = [NSMutableArray array];
        
            for (NSString *pdckey in keys) {
                
            for (WYShopCarModel *model in _data) {
                if ([model.car_new_id isEqualToString:[pdckey description]]) {
                    NSDictionary *ddc = pdcs[pdckey];
//                    model.car_id = ddc
                    model.car_id = ddc[@"id"];
                    //不变的id
                    model.car_new_id = ddc[@"sid"];
                    model.all_need = ddc[@"zongrenshu"];
                    model.left_need = ddc[@"shenyurenshu"];
                    model.qishu = ddc[@"qishu"];
                    
                    //如果购买数量大于剩余期数并且剩余期数小于1000那么就把购买期数改成剩余期数
                    //如果购买数量小于期数那么不变
                    
                    if((model.count > model.left_need.integerValue ) && (model.left_need.integerValue < 1001)){
                        model.count = (int)model.left_need.integerValue;
                    }
                    
                    
//                    if (model.left_need.intValue == 0){
//                        [_data removeObject:model];
//                        [[WYDataBase sharedDataBase]deletePdcInCarById:model.car_new_id.intValue];
//                    }
                    
                    if (model.left_need.intValue == 0){
                        [tmpArray addObject:model];
                    }
                    
                }
            }
                
                for (WYShopCarModel *tmpModel in tmpArray){
                    [_data removeObject:tmpModel];
                    [[WYDataBase sharedDataBase]deletePdcInCarById:tmpModel.car_new_id.intValue];
                }
        }
        _footer.PayBtn.enabled = YES;
        [_tableView headerEndRefreshing];
        //刷新去结算的数据
        _footer.data = _data;
        [_tableView reloadData];
    } failedBlock:^{
        _footer.PayBtn.enabled = YES ;
        [_tableView headerEndRefreshing];
    } needLog:NO];
}

//加载导航条
- (void)loadCustomNaviBar
{
    UIView *naviBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WYMWITH, 20+44)];
    naviBar.backgroundColor = QBB_RED_COLOR;
    
    //标题
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 25)];
    titleLab.center = CGPointMake(WYMWITH/2, 42);
    titleLab.text = @"购物车";
    titleLab.font = [UIFont systemFontOfSize:TITLE_SIZE];
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.textColor = [UIColor whiteColor];
    [naviBar addSubview:titleLab];
    //编辑按钮
    editBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [editBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [editBtn setTitle:@"取消" forState:UIControlStateSelected];
    [editBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [editBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [editBtn setTintColor:[UIColor clearColor]];
    [editBtn addTarget:self action:@selector(editBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    editBtn.frame = CGRectMake(WYMWITH - 50, 25, 40, 35);
    [naviBar addSubview:editBtn];
    
    [self.view addSubview:naviBar];
}
//编辑
- (void)editBtnOnClick
{
    if (_tableView.editing) {
        [_tableView setEditing:NO animated:YES];
    }else{
        [_tableView setEditing:YES animated:YES];
    }
    if (!editBtn.selected) {
        //取消所有选中
        for (WYShopCarModel *model in _data) {
            model.selectedFlag = NO;
        }
        [editFooter cancelSelect];
        if (!editFooter) {
            editFooter = [[[NSBundle mainBundle]loadNibNamed:@"EditFooterView" owner:self options:nil]lastObject];
            editFooter.father = self;
            editFooter.frame = CGRectMake(0, WYMHEIGHT - 49 - editFooter.frame.size.height, WYMWITH, editFooter.frame.size.height);
            [self.view addSubview:editFooter];
        }else{
            editFooter.hidden = NO;
        }
    }else{
        
        editFooter.hidden = YES;
        
    }
    editBtn.selected = !editBtn.selected;
    [_tableView reloadData];
    [_tableView setAllowsSelectionDuringEditing:YES];
    [editFooter updateCount];
}
//还原编辑前状态
- (void)cancelEdit
{
    [_tableView setEditing:NO animated:YES];
    editBtn.selected = NO;
}
//加载表格
- (void)loadTableView
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, WYMWITH, WYMHEIGHT - 64 - 49 -_footer.frame.size.height)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    //注册cell
    [_tableView registerNib:[UINib nibWithNibName:@"ShoppingCarCell" bundle:nil] forCellReuseIdentifier:@"ShoppingCarCell"];
    _tableView.rowHeight = 110.0;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.tableFooterView = [[UIView alloc]init];
    
    _data = [[NSMutableArray alloc]initWithArray:[[WYDataBase sharedDataBase]getAllpdcInCar]];
    [self.view addSubview:_tableView];
    //屏蔽键盘事件
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeKeyBoard)];
    tap.delegate = self;
    [_tableView addGestureRecognizer:tap];
    // 2.集成刷新控件
    [self setupRefresh];
}
/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    //    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // dateKey用于存储刷新时间，可以保证不同界面拥有不同的刷新时间
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing) dateKey:@"table"];
    //自动刷新(一进入程序就下拉刷新)
    [_tableView headerBeginRefreshing];
    
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    [self requestForNum];
}

//加载底部结算信息控件
- (void)loadBottomView
{
    _footer = [[[NSBundle mainBundle]loadNibNamed:@"PayView" owner:self options:nil]lastObject];
    _footer.frame = CGRectMake(0, WYMHEIGHT - 49 - _footer.frame.size.height, WYMWITH, _footer.frame.size.height);
    [self.view addSubview:_footer];
}
#pragma mark -- 表格协议函数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //刷新计数view的实现
    [self reloadFooter];
    if (_data.count == 0) {
        //创建购物车信息为空时的界面
        [self loadIntrestView];
        editBtn.hidden = YES;
    }else{
        [_intrestView removeFromSuperview];
        editBtn.hidden = NO;
    }
    return _data.count;
}
//刷新计数view的实现
-(void)reloadFooter
{
    [_intrestView removeFromSuperview];
    NSInteger allPrice = 0;
    for (WYShopCarModel *model in _data) {
        allPrice += model.count;
    }
    [_footer changeColorWithCount:_data.count andMoney:allPrice];
}

//生成indexPath下的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShoppingCarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShoppingCarCell"];
    if (_data.count > 0) {
        WYShopCarModel *model = self.data[indexPath.row];
        [cell fillCellWithModel:model];
        
        if (tableView.isEditing) {
            if(![cell viewWithTag:123123]){
                UIButton *selectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                selectBtn.frame = CGRectMake(6, 40, 25, 25);
                selectBtn.tag = 123123;
                selectBtn.userInteractionEnabled = NO;
                [selectBtn setImage:[UIImage imageNamed:@"icon_sel_del_normal"] forState:UIControlStateNormal];
                [selectBtn setImage:[UIImage imageNamed:@"icon_sel_del_press"] forState:UIControlStateSelected];
                selectBtn.selected = model.selectedFlag;
                [cell addSubview:selectBtn];
                
            }else{
                UIButton *btn = (UIButton *)[cell viewWithTag:123123];
                btn.selected = model.selectedFlag;
            }
        }else{
            UIView *btn = [cell viewWithTag:123123];
            [btn removeFromSuperview];
        }
    }
    cell.currentCellIndex = indexPath.row;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.father = self;
    return cell;
}

//cell选择时的操作
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.isEditing&&_data.count>0) {
        ShoppingCarCell *cell = (ShoppingCarCell *)[tableView cellForRowAtIndexPath:indexPath];
        UIButton *btn = (UIButton *)[cell viewWithTag:123123];
        btn.selected  = !btn.selected;
        
        WYShopCarModel *model = _data[indexPath.row];
        model.selectedFlag = btn.selected;
        
        [editFooter updateCount];
    }
}
//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!tableView.isEditing) {
        return UITableViewCellEditingStyleDelete;
    }
    return UITableViewCellEditingStyleNone;
}

//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    //弹出对话提示
    WYAlertView *altView = [WYAlertView showInView:self.view withTitle:@"温馨提示：" message:@"您确定将此产品移除购物车吗？" confirmButtonTitle:@"确定" cancelButtonTitle:@"取消"];
    [altView handleCancel:^{
        //表格退出编辑状态
        [tableView setEditing:NO animated:YES];
    } handleConfirm:^{
        //删除数据库中该产品记录
        WYShopCarModel *model = _data[indexPath.row];
        WYDataBase *database = [WYDataBase sharedDataBase];
        if ([database deletePdcInCarById:[model.car_new_id intValue]]) {
            //表格退出编辑状态
            [tableView setEditing:NO animated:YES];
            [_data removeObjectAtIndex:indexPath.row];
            //刷新表格 加动画删除当前行
            [tableView  deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:indexPath.row inSection:0]]  withRowAnimation:UITableViewRowAnimationFade];
            //刷新个数
            [[WYMainTabBarVC shareMainTaBarVC]updateCountToCar];
        }
    }];
    [altView show];
    
}
//修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"刪除";
}

//编辑数量时调整坐标
- (void)changeOffsetWithFrame:(CGRect)frame
{
    s_contOffet = _tableView.contentOffset;
    CGFloat flag = frame.origin.y - _tableView.contentOffset.y;
    if (flag > 100.0) {
        [UIView animateWithDuration:0.25 animations:^{
            _tableView.contentOffset = CGPointMake(0, frame.origin.y);
        }];
    }
}
//完成按钮点击时还原坐标
- (void)backOffset
{
    [UIView animateWithDuration:0.25 animations:^{
        _tableView.contentOffset = s_contOffet;
    }];
}
#pragma mark -- 关闭键盘
//关闭键盘
- (void)closeKeyBoard
{
    if ([self.view isFirstResponder]){
        
        ShoppingCarCell *cell = (ShoppingCarCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.currentCellIndex inSection:0]];
        [cell closeKeyBoardByVC];
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
        [_tableView reloadData];
        [self backOffset];
        
        
    }
}

//改写touch时间的委托方法 解决rowselected的冲突问题
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    
    if (_tableView.isEditing){
        
        return NO;
    }
    return  YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
